<template>
	<view  class="contain">
		<view v-if="data.length !== 0" style="display: flex;justify-content: center;" v-for="(item, index) in data" :key="item._id">
			<view class="box" @click="to_publish(item)">
				<view style="font-weight: bold;margin-top: 10rpx;margin-left: 10rpx;">笔记草稿</view>
				<view style="margin-left: 10rpx;">{{item.title}}</view>
				<view style="margin-left: 10rpx;padding-bottom: 10rpx;" class="solids-bottom">{{item.content}}</view>
				<view style="margin-left: 10rpx;margin-bottom: 10rpx;">
					<view style="float: left;">{{item.time}} 写笔记保存草稿</view>
					<text class="cuIcon-delete"  style="float: right;margin-right: 10rpx;z-index: 999;"
						@click.stop="delete_drafts(item._id,index)"></text>
				</view>
			</view>
		</view>
		<view v-if="data.length == 0"><image style="width: 100%;" src="../../static/images/empty.png" mode="widthFix"></image></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				data: [],
				openid: ""
			};
		},
		onLoad() {
			this.openid = uni.getStorageSync('openid')
			let _this = this
			const db = uniCloud.database()
			console.log(this.openid)
			let res = db.collection('drafts').where({
				openid: _this.openid
			}).get().then(res => {
				console.log(res.result.data)
				_this.data = res.result.data
				_this.data.reverse()
			})
		},
		methods: {
			// 删除草稿
			delete_drafts: function(_id,e) {
				console.log(_id)
				console.log(e)
				let _this = this
				uni.showModal({
					title: '确认删除吗',
					success: function(res) {
						if (res.confirm) {
							// 删除最后一个元素
							if(_this.data.length === 1) {
									_this.data.pop()
							}
							else {
								_this.data.splice(_this.data.length-e,1)
							}
							const db = uniCloud.database();
							db.collection("drafts").doc(_id).remove()
						} else if (res.cancel) {

						}
					}
				});
			},
			// 去到发布页面
			to_publish: function(e) {
				uni.navigateTo({
				  url: '/pages/publish_recommend/index',
				  success: function(res) {
				    // 通过eventChannel向被打开页面传送数据
				    res.eventChannel.emit('acceptDataFromOpenerPage', { data: e })
				  }
				})
			}
		}
	}
</script>

<style lang="scss">
	.contain {
		display: flex;
		justify-content: start;
		flex-direction: column;

	}

	.box {
		height: 220rpx;
		border-radius: 10rpx;
		width: 90%;
		display: flex;
		justify-content: space-between;
		flex-direction: column;
		box-shadow: 0 0 30rpx lightgray;
		margin-top: 20rpx;
	}
</style>
